<script setup lang="ts">
import { saveRoleApi } from "@/api/role";
import { ref } from "vue";

class RoleForm {
  name = "";
  menu = [];
}

const treeRef = ref<any>();

const roleForm = ref(new RoleForm());
const isEditor = ref(false);
const visible = ref(false);

const props = defineProps({
  menuData: {
    type: Array,
    default: () => [],
  },
});

const open = (data: any) => {
  visible.value = true;
  if (data) {
    isEditor.value = true;
    setTimeout(() => {
      roleForm.value = data;
    }, 0);
  } else {
    isEditor.value = false;
    roleForm.value = new RoleForm();
  }
};

const beforeClose = (deno: any) => {
  deno();
};
const submitForm = async () => {
  const menuTree = treeRef.value.getCheckedKeys();
  // console.log(menuTree);
  roleForm.value.menu = menuTree;
  const res = await saveRoleApi(roleForm.value);
  console.log(res);
};

const updateUser = () => {
  submitForm()
};

const handleCheckChange = () => {
  // console.log(a);
};

const check = (data: any,key: any) => {
  console.log(data);  
  console.log(key);  
};

const treeProps = {
  children: "children",
  label: (data: any) => {
    return data.meta.title;
  },
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    :before-close="beforeClose"
    v-model="visible"
    title="角色"
    :with-header="false"
  >
    <el-form
      ref="userFormRef"
      label-position="left"
      label-width="auto"
      :model="roleForm"
      style="max-width: 600px"
    >
      <el-form-item label="菜单权限">
        <el-tree
          @check="check"
          ref="treeRef"
          :data="props.menuData"
          node-key="id"
          show-checkbox
          @check-change="handleCheckChange"
          :props="treeProps"
        />
      </el-form-item>
      <el-form-item label="角色名称">
        <el-input v-model="roleForm.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer v-slot="scope">
      <div class="drawer-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button v-if="!isEditor" type="primary" @click="submitForm"
          >添加</el-button
        >
        <el-button v-else type="primary" @click="updateUser">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped lang="less"></style>
